package com.siderakis.gwt.cellwidgets.client;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.siderakis.gwt.cellwidgets.shared.HasPercentage;

/**
 * 
 * @author Nick Siderakis
 * 
 * */
public class StatusCell<C> extends AbstractCell<C> {

	public static interface Delegate<T> {
		void execute(T object);
	}

	public interface StatusCellSafeHTMLTemplate extends SafeHtmlTemplates {
		@Template("<div><div style=\"height:1.2em;width:100%;cursor:default;border:thin #7ba5d5 solid;\">"
				+ "<div style=\"height:1.2em;width:{0}%; background-image: url('images/progress_background.png');\">"
				+ "</div><div style=\"height:1.2em; margin:-1.2em;font-weight:bold;color:#4e7fba;\">"
				+ "<center>{0}%</center></div></div></div>")
				SafeHtml status(int percentage);
	}


	private final Delegate<C> delegate;

	private static final StatusCellSafeHTMLTemplate TEMPLATE = GWT
	.create(StatusCellSafeHTMLTemplate.class);

	public StatusCell(final Delegate<C> delegate) {
		super("click");
		this.delegate = delegate;
	}

	@Override
	public void onBrowserEvent(final Element parent, final C value,
			final Object key, final NativeEvent event,
			final ValueUpdater<C> valueUpdater) {
		if ("click".equals(event.getType())) {
			delegate.execute(value);
		}
	}

	@Override
	public void render(final C value, final Object key, final SafeHtmlBuilder sb) {
		final Integer per = value == null ? 0 : ((HasPercentage) value)
				.getPercentage();
		sb.append(per == null ? TEMPLATE.status(0) : TEMPLATE.status(per));
	}

}
